#import "CTSetPwdVC.h"
#import "CTPasswordView.h"
#import "M80AttributedLabel.h"
#import "CTHomeVC.h"
#import "CTPrivacyVC.h"
#import "CTLoginVC.h"
@interface CTSetPwdVC ()
@property (nonatomic ,strong) UILabel *titleLabel;
@property (nonatomic ,strong) UILabel *subTitleLabel;
@property (nonatomic ,strong) CTPasswordView *pwdView;
@property (nonatomic ,strong) UIButton *loginButton;  
@property (nonatomic ,strong) UIButton *protocolButton;
@property (nonatomic ,strong) M80AttributedLabel *protocolLabel;
@property (nonatomic ,strong) UIButton *serviceButton;
@property (nonatomic ,strong) UIButton *qxhButton;
@end
@implementation CTSetPwdVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setConstrains];
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kpage_login,
        @"elementUniqueIdentifier"  : kpage_login,
        @"referenceIdentification" : @"",
    };
    [CTUploadManager ct_uploadType:CTUploadTypePage data:data];
}
- (void)setUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self ct_showCustomerNavBarWithType:WBNavBarTypeNormal];
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.subTitleLabel];
    [self.view addSubview:self.pwdView];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.protocolButton];
    [self.view addSubview:self.protocolLabel];
    BOOL showOnlineService = [[NSUserDefaults standardUserDefaults] boolForKey:kShowOnlineService];
    if (showOnlineService) {
        [self.view addSubview:self.serviceButton];
        [self.view addSubview:self.qxhButton];
        [self.qxhButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.view.mas_centerX).offset(Ratio(-6));
            make.bottom.mas_equalTo(-[UIDevice ct_safeBottom]-Ratio(40));
        }];
        [self.serviceButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view.mas_centerX).offset(Ratio(6));
            make.bottom.mas_equalTo(-[UIDevice ct_safeBottom]-Ratio(40));
        }];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDismissKeyboard:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    @weakify(self);
    [[self.pwdView.contentTF rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(id x) {
        @strongify(self);
        [self loginObserve];
    }];
}
- (void)loginObserve {
    if (self.pwdView.contentTF.text.length > 6) {
        self.pwdView.contentTF.text = [self.pwdView.contentTF.text substringWithRange:NSMakeRange(0, 6)];
    }
    BOOL canSet = (self.pwdView.contentTF.text.length == 6);
    self.loginButton.userInteractionEnabled = canSet ? YES : NO;
    [self.loginButton setBackgroundColor:canSet ? [UIColor colorFF6C2E] : [UIColor colorCCC]];
}
- (void)tapDismissKeyboard:(id)sender {
    [self.view endEditing:YES];
}
- (void)ct_navBackButtonClicked:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark - set pwd
- (void)setPwdButtonClick {
    if (![self.pwdView.contentTF.text isPwdFormated]) {
        return;
    }
    if (!self.protocolButton.selected) {
        __weak typeof(self) weakself = self;
        TJAlertView *aAlertView = [TJAlertView alertWithTitle:@"" subTitle:@"Thank you for using productName. Before using productName, please read Privacy Policy and Loan Terms to understand how we collect, use and store your data to understand the responsibilities and obligations of each party, and other detailed information.If you agree, you can turn on our service. If you choose to decline, we will not be able to serve you." clickTitle:@"Privacy Policy" clickSecond:@"Loan Terms" click:^(NSString * _Nonnull title) {
            NSString *url = @"";
            if ([title isEqualToString:@"Privacy Policy"]) {
                url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].privacyPolicyUrl];
            } else {
                url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].userAgreementUrl];
            }
            CTPrivacyVC *webVc = [[CTPrivacyVC alloc] initWithTitle:@"" gotoUrl:url];
            [webVc showLeftSingleBack];
            [self.navigationController pushViewController:webVc animated:YES];
        }];
        TJAlertViewAction *aCancelAction = [TJAlertViewAction actionWithTitle:@"Refused" titleColor:[UIColor color161616] backGroudColor:[UIColor whiteColor] handler:nil];
        TJAlertViewAction *aSureAction = [TJAlertViewAction actionWithTitle:@"I have read and accept" titleColor:[UIColor colorFF6C2E] backGroudColor:[UIColor whiteColor] handler:^(TJAlertViewAction *action) {
            weakself.protocolButton.selected = !weakself.protocolButton.selected;
            [weakself setPwdRequest];
        }];
        [aAlertView doAddAction:aCancelAction];
        [aAlertView doAddAction:aSureAction];
        [aAlertView doShowAlertView];
        return;
    }
    [self setPwdRequest];
}
- (void)setPwdRequest {
    NSDictionary *paramDic = @{
        @"patronIdentifier" : [CTUserManager ct_getZuid],
        @"patronCategory" : @"1",
        @"clientSoftwareIndicator" : @"",
        @"accessCode" : returnBeNil(self.pwdView.contentTF.text),
        @"wirelessDeviceNumber" : returnBeNil([CTUserManager shareManager].userModel.wirelessDeviceNumber),
        @"retreatPhone" : [CTUserManager shareManager].userModel.wirelessDeviceNumber,
        @"concessionType" : @(CTOperationTypeRegister),
        @"cipherToken" : returnBeNil(self.codeToken),
        @"visualCheckCode" : returnBeNil(self.verifyCode),
        @"requiresSaveVerification" : @(1),
        @"uniqueZuid" : @"",
        @"googleUserGroupID" : @"",
        @"emailServiceAccount" : @"",
        @"referralKey" : @"",
        @"channelUserGroupID" : @"",
        @"collectiveUserGroupID" : @"",
        @"discountCertificateGroupID" : @"",
        @"voucherPresentationMode" : @"",
        @"expansionInformation" : @"",
        @"accessPermissionToken" : @"",
    };
    [self.view showLoading];
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/seedSow", CTPathTypePost, nil) parametersDic:paramDic success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        [self.view dismissLoading];
        if (!isSuccess) {
            [self.view showInfoText:(NSString *)responseObject];
        } else {
            CTUserModel *uerModel = [CTUserModel modelWithDictionary:responseObject[@"matterContent"]];
            CTUserModel *localModel = [CTUserManager shareManager].userModel;
            localModel.accountStatusFreeze = uerModel.accountStatusFreeze;
            localModel.userGroup = uerModel.userGroup;
            localModel.userEntityId = uerModel.userEntityId;
            localModel.userSpecificId = uerModel.userSpecificId;
            localModel.uniqueFlag = uerModel.userEntityId;
            localModel.userAffirmationStatus = uerModel.userAffirmationStatus;
            localModel.userAuthenticationToken = uerModel.userAuthenticationToken;
            localModel.temporalIndicator = uerModel.userAuthenticationToken;
            localModel.validationToken = uerModel.validationToken;
            localModel.isUserLoggedIn = YES;
            [[CTUserManager shareManager] userLogin:localModel];
            [CTUploadManager ct_uploadType:CTUploadTypeDevice];
            [CTUploadManager ct_uploadType:CTUploadTypeLocation];
            [CTUploadManager ct_uploadType:CTUploadTypeLogin];
            [CTUploadManager ct_uploadType:CTUploadTypeRegister];
            [CTAFManager logEvent:LC_registrationSuccess];
            [CTAFManager logEvent:LC_selfRegistrationSuccess];
        }
    }];
}
- (void)setConstrains {
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Ratio(24));
        make.top.mas_equalTo([UIDevice ct_fullNavHeight]+Ratio(30));
    }];
    [self.subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Ratio(24));
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(Ratio(24));
    }];
    [self.pwdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(Ratio(24));
        make.right.mas_equalTo(self.view).offset(Ratio(-24));
        make.top.mas_equalTo(self.subTitleLabel.mas_bottom).offset(Ratio(44));
        make.height.mas_equalTo(Ratio(44));
    }];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Ratio(30));
        make.top.mas_equalTo(self.pwdView.mas_bottom).offset(Ratio(65));
        make.height.mas_equalTo(Ratio(52));
        make.right.mas_equalTo(Ratio(-30));
    }];
    [self.protocolButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(Ratio(16));
        make.left.mas_equalTo(self.view).offset(Ratio(24));
        make.width.height.mas_equalTo(Ratio(20));
    }];
    [self.protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.protocolButton.mas_top).offset(Ratio(2));
        make.left.mas_equalTo(self.protocolButton.mas_right).offset(Ratio(6));
        make.right.mas_lessThanOrEqualTo(self.view).offset(Ratio(-26));
        make.height.mas_equalTo(Ratio(62));
    }];
}
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.numberOfLines = 1;
        _titleLabel.font = [UIFont systemFontOfSize:Ratio(20) weight:UIFontWeightBold];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.text = @"Please set login password";
    }
    return _titleLabel;
}
- (UILabel *)subTitleLabel {
    if (!_subTitleLabel) {
        _subTitleLabel = [[UILabel alloc] init];
        _subTitleLabel.numberOfLines = 1;
        _subTitleLabel.font = [UIFont systemFontOfSize:Ratio(11) weight:UIFontWeightMedium];
        _subTitleLabel.textColor = [UIColor colorFF8724];
        _subTitleLabel.textAlignment = NSTextAlignmentLeft;
        CTUserModel *localModel = [CTUserManager shareManager].userModel;
        _subTitleLabel.text = [localModel.wirelessDeviceNumber maskedPhoneNumber];
    }
    return _subTitleLabel;
}
- (CTPasswordView *)pwdView {
    if (!_pwdView) {
        _pwdView = [[CTPasswordView alloc] initWithPlaceHolder:@"Please enter six letters or numbers"];
        __weak typeof(self) weakSelf = self;
        _pwdView.editDidEndBlock = ^(CTPasswordView * _Nonnull cell, CTTFModel * _Nonnull tfModel) {
            tfModel.navigationRoute = NSStringFromClass(weakSelf.class);
            tfModel.pageIdentity = ktf_login_sms;
            tfModel.elementUniqueIdentifier = ktf_login_sms;
            NSDictionary *data = [tfModel model_keyValues];
            [CTUploadManager ct_uploadType:CTUploadTypeTF data:data];
        };
    }
    return _pwdView;
}
- (UIButton *)loginButton
{
    if (!_loginButton) {
        _loginButton = [[UIButton alloc] init];
        [_loginButton setBackgroundColor:[UIColor colorCCC]];
        [_loginButton setTitleColor: [UIColor whiteColor] forState:UIControlStateNormal];
        _loginButton.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Medium" size:Ratio(20)];
        [_loginButton setTitle:@"Log in" forState:UIControlStateNormal];
        _loginButton.layer.cornerRadius = Ratio(26);
        _loginButton.layer.masksToBounds = YES;
        [_loginButton addTarget:self action:@selector(setPwdButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}
- (UIButton *)protocolButton
{
    if (_protocolButton == nil) {
        _protocolButton = [[UIButton alloc] init];
        [_protocolButton setImage:[UIImage imageNamed:@"login_unsel"] forState:UIControlStateNormal];
        [_protocolButton setImage:[UIImage imageNamed:@"login_sel"] forState:UIControlStateSelected];
        _protocolButton.selected = YES;
        @weakify(self);
        [[_protocolButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            @strongify(self);
            self.protocolButton.selected = !self.protocolButton.selected;
        }];
    }
    return _protocolButton;
}
- (M80AttributedLabel *)protocolLabel
{
    if (_protocolLabel == nil) {
        NSString *privacyString = @"I have read and accept Privacy Policy and  Loan Terms.";
        _protocolLabel = [[M80AttributedLabel alloc]initWithFrame:CGRectZero];
        _protocolLabel.textColor = [UIColor blackColor];
        _protocolLabel.linkColor = [UIColor colorFF6C2E];
        _protocolLabel.backgroundColor = [UIColor clearColor];
        _protocolLabel.highlightColor = [UIColor clearColor];
        _protocolLabel.font = [UIFont systemFontOfSize:13];
        _protocolLabel.underLineForLink = NO;
        _protocolLabel.contentMode = UIViewContentModeLeft;
        _protocolLabel.textAlignment = kCTTextAlignmentLeft;
        _protocolLabel.numberOfLines = 0;
        _protocolLabel.text = privacyString;
        NSRange range1  = [privacyString rangeOfString:@"Privacy Policy"];
        [_protocolLabel addCustomLink:[NSValue valueWithRange:range1] forRange:range1];
        NSRange range2  = [privacyString rangeOfString:@"Loan Terms"];
        [_protocolLabel addCustomLink:[NSValue valueWithRange:range2] forRange:range2];
        _protocolLabel.delegate = self;
    }
    return _protocolLabel;
}
#pragma mark - M80label
- (void)m80AttributedLabel:(M80AttributedLabel *)label clickedOnLink:(id)linkData
{
    NSString *rangeStr =[NSString stringWithFormat:@"%@",linkData];
    NSString *url = @"";
    NSString *title = @"";
    if ([rangeStr containsString:@"14"]){
        url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].privacyPolicyUrl];
    }else if ([rangeStr containsString:@"10"]){
        url = [NSURL fullUrlStringForWeb:[CTEnvironmentManager shareManager].userAgreementUrl];
    }
    CTPrivacyVC *webVc = [[CTPrivacyVC alloc] initWithTitle:title gotoUrl:url];
    [webVc showLeftSingleBack];
    [self.navigationController pushViewController:webVc animated:YES];
}
- (UIButton *)qxhButton
{
    if (!_qxhButton) {
        _qxhButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _qxhButton.titleLabel.font = kBoldFontSize(13);
        [_qxhButton setTitleColor:[UIColor colorFF6C2E] forState:UIControlStateNormal];
        [_qxhButton setTitle:@"  Switch account" forState:UIControlStateNormal];
        [_qxhButton setImage:[UIImage imageNamed:@"login_refresh"] forState:(UIControlStateNormal)];
        _qxhButton.contentMode = UIViewContentModeLeft;
        [_qxhButton addTarget:self action:@selector(switchAccount) forControlEvents:UIControlEventTouchUpInside];
    }
    return _qxhButton;
}
- (UIButton *)serviceButton
{
    if (!_serviceButton) {
        _serviceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _serviceButton.titleLabel.font = kBoldFontSize(13);
        [_serviceButton setTitleColor:[UIColor colorFF6C2E] forState:UIControlStateNormal];
        [_serviceButton setTitle:@"  Online services" forState:UIControlStateNormal];
        [_serviceButton setImage:[UIImage imageNamed:@"customer_service"] forState:(UIControlStateNormal)];
        _serviceButton.contentMode = UIViewContentModeLeft;
        [_serviceButton addTarget:self action:@selector(onlineService) forControlEvents:UIControlEventTouchUpInside];
    }
    return _serviceButton;
}
- (void)switchAccount {
    for (UIViewController *aVC in self.navigationController.viewControllers) {
        if ([aVC isKindOfClass:[CTLoginVC class]]) {
            CTLoginVC *loginVC = (CTLoginVC *)aVC;
            loginVC.phoneView.contentTF.text = @"";
            [self.navigationController popToViewController:loginVC animated:YES];
            return;;
        }
    }
}
- (void)onlineService {
    NSDictionary *data = @{
        @"navigationRoute" : NSStringFromClass(self.class),
        @"pageIdentity" : kbtn_login_service,
        @"elementUniqueIdentifier"  : kbtn_login_service,
    };
    [CTUploadManager ct_uploadType:CTUploadTypeBTN data:data];
    NSString *fullUrl = [NSURL fullUrlStringForWeb:@"#/onlineservice"];
    CTHomeVC *webVc = [[CTHomeVC alloc] initWithTitle:@"Online services" gotoUrl:fullUrl];
    [webVc showLeftSingleBack];
    [self.navigationController pushViewController:webVc animated:YES];
}
@end
